package com.qf.filter;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/23 9:17
 */
@WebFilter(filterName = "AutoFilter",urlPatterns = "/index.jsp")
public class AutoFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //类型转换
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //1当前是否已经登录
        User user= (User) request.getSession().getAttribute("user");
        if(user!=null){
            //放行
            chain.doFilter(req, resp);
            return;
        }
        //2获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("userinfo")){
                    //获取值
                    String userinfo = cookie.getValue();
                    //Base64解密
                    try {
                        byte[] decode = Base64.getDecoder().decode(userinfo);
                        userinfo=new String(decode,"utf-8");
                        System.out.println("userinfo:"+userinfo);
                        String[] arr = userinfo.split("#");
                        //创建业务对象
                        UserService userService=new UserServiceImpl();
                        User u=userService.login(arr[0],arr[1]);
                        request.getSession().setAttribute("user", u);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //删除cookie
                        cookie.setPath(request.getContextPath());
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
